﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Xml.Serialization;

namespace BoatXtend
{
    public static class Extensions
    {
        public static int LesserOf(int x, int y)
        {
            int rtn = x;
            if (y < x)
            {
                rtn = y;
            }
            return rtn;
        }

        public static int GreaterOf(int x, int y)
        {
            int rtn = x;
            if (y > x)
            {
                rtn = y;
            }
            return rtn;
        }
    }

    public static class BoolExtensions
    {
        const string Affirmative = "Yes";
        const string Negative = "No";

        public static int ToInt(this bool value)
        {
            int rtn = 0;
            if (value)
            {
                rtn = 1;
            }
            return rtn;
        }

        public static string ToFriendlyString(this bool value)
        {
            if (value)
            {
                return Affirmative;
            }
            else
            {
                return Negative;
            }
        }
    }

    public static class ByteArrayExtensions
    {
        public static string ToHexString(this Byte[] value)
        {
            string hex = BitConverter.ToString(value);
            return hex.Replace("-", "");
        }
    }

    public static class DataTableExtensions
    {
        // --- Row Level ---
        public static NameValueCollection GetDifference(this DataRow value, DataRow newValue)
        {
            return value.GetDifference(newValue, "");
        }

        public static NameValueCollection GetDifference(this DataRow value, DataRow newValue, string rowIdentifierPrefix)
        {
            NameValueCollection rtn = new NameValueCollection();
            if (value.Table.SchemaEquals(newValue.Table))
            {
                for (int i = 0; i < value.Table.Columns.Count; i++)
                {
                    if (value[i].ToString() != newValue[value.Table.Columns[i].ColumnName].ToString())
                    {
                        rtn.Add(value.Table.Columns[i].ColumnName, value[i].ToString());
                    }
                }
            }
            return rtn;
        }

        // --- Table Level ---
        public static NameValueCollection GetDifference(this DataTable value, DataTable newValue, string keyColumnName)
        {
            NameValueCollection rtn = new NameValueCollection();
            if (value.SchemaEquals(newValue))
            {
                for (int i = 0; i < value.Rows.Count; i++)
                {
                    for (int j = 0; j < newValue.Rows.Count; j++)
                    {
                        if (value.Rows[i][keyColumnName].ToString() ==
                            newValue.Rows[j][keyColumnName].ToString())
                        {
                            //we've found a matching row, now find differences
                            rtn.Add(value.Rows[i].GetDifference(newValue.Rows[j], i.ToString()));
                        }
                    }
                }
            }
            return rtn;
        }

        public static bool SchemaEquals(this DataTable dt, DataTable value)
        {
            if (dt.Columns.Count != value.Columns.Count)
                return false;

            var dtColumns = dt.Columns.Cast<DataColumn>();
            var valueColumns = value.Columns.Cast<DataColumn>();


            var exceptCount = dtColumns.Except(valueColumns, DataColumnEqualityComparer.Instance).Count();
            return (exceptCount == 0);
        }

        class DataColumnEqualityComparer : IEqualityComparer<DataColumn>
        {
            #region IEqualityComparer Members

            private DataColumnEqualityComparer() { }
            public static DataColumnEqualityComparer Instance = new DataColumnEqualityComparer();


            public bool Equals(DataColumn x, DataColumn y)
            {
                if (x.ColumnName != y.ColumnName)
                    return false;
                if (x.DataType != y.DataType)
                    return false;

                return true;
            }

            public int GetHashCode(DataColumn obj)
            {
                int hash = 17;
                hash = 31 * hash + obj.ColumnName.GetHashCode();
                hash = 31 * hash + obj.DataType.GetHashCode();

                return hash;
            }

            #endregion
        }
    }

    public static class DateTimeExtensions
    {
        public static int LastDayOfMonth(this DateTime value)
        {
            DateTime firstOfNextMonth = new DateTime(value.Year, value.Month, 1);
            return firstOfNextMonth.AddMonths(1).AddDays(-1).Day;
        }

        public static DateTime MakeSQLMaxValue(this DateTime value)
        {
            return new DateTime(9999, 12, 12, 23, 59, 59);
        }

        public static DateTime MakeSQLMinValue(this DateTime value)
        {
            return new DateTime(1753, 1, 1);
        }

        public static DateTime MakeSQLSafe(this DateTime date)
        {
            if (date < new DateTime().MakeSQLMinValue())
            {
                date = date.MakeSQLMinValue();
            }
            if (date > new DateTime().MakeSQLMaxValue())
            {
                date = date.MakeSQLMaxValue();
            }
            return date;
        }

        public static string ToSQLString(this DateTime date)
        {
            return date.ToString("yyyy-dd-MM HH:mm:ss.zzz");
        }
    }

    public static class DecimalExtensions
    {
        public static decimal RoundMoney(this decimal value)
        {
            return Math.Round(value, 2);
        }

        public static double ToDouble(this decimal value)
        {
            return Convert.ToDouble(value);
        }

        public static string ToMoneyString(this decimal value)
        {
            return String.Format("{0:C}", value);
        }
    }

    public static class HttpWebRequestExtensions
    {
        public static void SendRequest(this HttpWebRequest value, string requestArgs)
        {
            /*
            string requestArgs =
                "&case_num=" + caseNumLong +
                "&date_from=1/1/1900" +
                "&terminated_parties=on" +
                "&output_format=html";*/

            // Add form parameters (this is via POST method)
            Stream requestStream = value.GetRequestStream();
            StreamWriter requestWriter = new StreamWriter(requestStream, Encoding.ASCII);
            requestWriter.Write(requestArgs);       //write data into the request stream
            requestWriter.Close();                  //close underlying write stream
            requestStream.Close();                  //close underlying request stream
            requestStream.Dispose();                //send the request
        }

        public static string GetResponseString(this HttpWebRequest value, bool sendFirst)
        {
            if (sendFirst)
            {
                value.SendRequest("");
            }
            HttpWebResponse response = (HttpWebResponse)value.GetResponse();
            string rtn = "";
            using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
            {
                rtn = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
            }
            return rtn;
        }
    }

    public static class IntExtensions
    {
        public static bool ToBool(this int value)
        {
            bool rtn = false;
            if (value != 0)
            {
                rtn = true;
            }
            return rtn;
        }

        public static string ToFriendlyString(this int value)
        {
            if (value == 0)
            {
                return false.ToFriendlyString();
            }
            else
            {
                return true.ToFriendlyString();
            }
        }
    }

    public static class ISerializableExtensions
    {
        public static string GetXmlString<T>(this T value)
        {
            XmlSerializer xml = new XmlSerializer(value.GetType());
            StringWriter writer = new StringWriter();
            xml.Serialize(writer, value);
            return writer.ToString();
        }
    }

    public static class ObjectExtensions
    {
        public static bool IsType(this object value, Type type)
        {
            bool rtn = false;
            if (value.GetType() == type)
            {
                rtn = true;
            }
            return rtn;
        }
    }

    public static class RandomExtentions
    {
        public static string NextString(this Random value)
        {
            return NextString(value, 22);
        }

        public static string NextString(this Random value, int length)
        {
            int iterations = length / 22;
            if (iterations == 0 | length % 22 > 0)
            {
                iterations++;
            }
            string rtn = "";
            Guid tmp = new Guid();
            for (int i = 0; i < iterations; i++)
            {
                rtn += Convert.ToBase64String(tmp.ToByteArray());
            }
            rtn = rtn.RemoveAllInstances("=");
            rtn = rtn.RemoveAllInstances("+");
            rtn = rtn.Truncate(length);
            return rtn;
        }
    }

    public enum StringFormat
    {
        None,
        Money,
        PhoneNumber,
        SSN,
        ZIP
    }

    public static class StringExtensions
    {
        public static string CleanFromTextMask(this string value)
        {
            value = value.RemoveAllInstances("_");
            value = value.RemoveAllInstances("-");
            value = value.Trim();
            return value;
        }

        public static object Deserialize<T>(this string value)
        {
            XmlSerializer xml = new XmlSerializer(value.GetType());
            StringReader reader = new StringReader(value);
            object rtn = xml.Deserialize(reader);
            return (T)rtn;
        }

        public static string EmptyIf(this string value, string instance)
        {
            if (value == instance)
            {
                value = string.Empty;
            }
            return value;
        }

        public static string EnforceDateTime(this string value)
        {
            DateTime tmp = new DateTime().MakeSQLMinValue();
            if (!DateTime.TryParse(value, out tmp))
            {
                value = tmp.ToString();
            }
            return value;
        }

        public static string EnforceDecimal(this string value)
        {
            decimal tmp = 0;
            if (!string.IsNullOrEmpty(value.Trim().RemoveAllInstances(".").RemoveAllInstances("0")))
            {
                if (!decimal.TryParse(value, out tmp))
                {
                    value = tmp.ToString();
                }
            }
            if (tmp == 0)
            {
                value = tmp.ToString();
            }
            return value;
        }

        public static string EnforceInt(this string value)
        {
            int tmp = 0;
            if (!int.TryParse(value, out tmp))
            {
                value = tmp.ToString();
            }
            return value;
        }

        public static DateTime EnforceToDateTime(this string value)
        {
            return Convert.ToDateTime(value.EnforceDateTime());
        }

        public static decimal EnforceToDecimal(this string value)
        {
            return Convert.ToDecimal(value.EnforceDecimal());
        }

        public static int EnforceToInt(this string value)
        {
            return Convert.ToInt32(value.EnforceInt());
        }

        public static string Format(this string value, StringFormat format)
        {
            switch (format)
            {
                case StringFormat.None:
                    break;
                case StringFormat.Money:
                    value = String.Format("{0:N}", value);
                    break;
                case StringFormat.PhoneNumber:
                    if (value.Length >= 7)
                    {

                    }
                    if (value.Length >= 10)
                    {

                    }
                    break;
                default:
                    break;
            }
            return value;
        }

        public static string GetQueryStringValue(this string value, string queryKey)
        {
            string[] prefixes = { "?", "&" };
            bool gotValue = false;
            for (int i = 0; i < prefixes.Length; i++)
            {
                if (value.Contains(prefixes[i] + queryKey + "="))
                {
                    gotValue = true;
                    value = value.RemoveUntilFirst(prefixes[i] + queryKey + "=", true);
                    if (value.Contains("&"))
                    {
                        value = value.RemoveAtFirst("&");
                    }
                }
            }
            if (!gotValue)
            {
                value = "";
            }
            return value;
        }

        public static string Harvest(this string value, string prefix, string suffix, bool inclusive, int prefixIndex, int suffixIndex)
        {
            if (value.Contains(prefix) & value.Contains(suffix) &
                prefixIndex < value.InstancesOf(prefix) &
                suffixIndex < value.InstancesOf(suffix))
            {
                if (value.IndicesOf(prefix)[prefixIndex] < value.IndicesOf(suffix)[suffixIndex])
                {
                    value = value.Remove(0, value.IndicesOf(prefix)[prefixIndex]);
                    value = value.Remove(value.IndicesOf(suffix)[suffixIndex] + suffix.Length);
                    if (!inclusive)                             //include the prefix/suffix?
                    {
                        value = value.RemoveFirst(prefix);      //trim off prefix
                        value = value.RemoveLast(suffix);       //trim off suffix
                    }
                }
            }
            return value;
        }

        public static string HarvestRemove(this string value, string prefix, string suffix, bool inclusive, int prefixIndex, int suffixIndex)
        {
            if (value.Contains(prefix) & value.Contains(suffix) &
                prefixIndex < value.InstancesOf(prefix) &
                suffixIndex < value.InstancesOf(suffix))
            {
                if (value.IndicesOf(prefix)[prefixIndex] < value.IndicesOf(suffix)[suffixIndex])
                {
                    value = value.Remove(
                        value.IndicesOf(prefix)[prefixIndex] + prefix.Length, value.IndicesOf(suffix)[suffixIndex] - value.IndicesOf(prefix)[prefixIndex] - prefix.Length);
                    if (!inclusive)                             //include the prefix/suffix?
                    {
                        value = value.RemoveFirst(prefix);      //trim off prefix
                        value = value.RemoveLast(suffix);       //trim off suffix
                    }
                }
            }
            return value;
        }

        public static string HtmlDecode(this string value)
        {
            return HttpUtility.HtmlDecode(value);
        }

        public static string HtmlEncode(this string value)
        {
            return HttpUtility.HtmlEncode(value);
        }

        public static List<int> IndicesOf(this string value, string instance)
        {
            List<int> rtn = new List<int>();
            int offset = 0;
            for (int i = 0; i < value.InstancesOf(instance); i++)
            {
                rtn.Add(value.IndexOf(instance) + offset);
                offset += value.IndexOf(instance) + instance.Length;
            }
            return rtn;
        }

        public static string InsertBeforeFirst(this string value, string insertText, string instance)
        {
            if (value.Contains(instance))
            {
                value.Insert(value.IndexOf(instance), insertText);
            }
            return value;
        }

        public static string InsertEnumSpaces(this string value)
        {
            if (String.IsNullOrEmpty(value))
            {
                return value;
            }
            StringBuilder newText = new StringBuilder(value.Length * 2);
            newText.Append(value[0]);
            for (int i = 1; i < value.Length; i++)
            {
                if (char.IsUpper(value[i]) && value[i - 1] != ' ')
                {
                    newText.Append(' ');
                }
                newText.Append(value[i]);
            }
            return newText.ToString();
        }

        public static int InstancesOf(this string value, string instance)
        {
            int rtn = 0;
            while (value.Contains(instance))
            {
                value = value.Remove(0, value.IndexOf(instance) + instance.Length);
                rtn++;
            }
            return rtn;
        }

        public static bool IsDateTime(this string value)
        {
            DateTime tmp = new DateTime();
            return DateTime.TryParse(value, out tmp);
        }

        public static bool IsInt(this string value)
        {
            int tmp = 0;
            return int.TryParse(value, out tmp);
        }

        public static string JsonSafe(this string value)
        {
            string[] badchars = { ",", "\"", "'" };
            string[] goodchars = { "&#44;", "&quot;", "&#39;" };

            for (int i = 0; i < badchars.Length; i++)
            {
                value = value.Replace(badchars[i], goodchars[i]);
            }

            return value;
        }

        public static string Left(this string value, int numChars)
        {
            return value.Truncate(numChars);
        }

        public static string NullIf(this string value, string instance)
        {
            if (value == instance)
            {
                value = null;
            }
            return value;
        }

        public static string Prefix(this string value, string prefix)
        {
            return prefix + value;
        }

        private static string RegexReplace(this string stringValue, string matchPattern, string toReplaceWith)
        {
            return Regex.Replace(stringValue, matchPattern, toReplaceWith);
        }

        private static string RegexReplace(this string stringValue, string matchPattern, string toReplaceWith, RegexOptions regexOptions)
        {
            return Regex.Replace(stringValue, matchPattern, toReplaceWith, regexOptions);
        }

        // ****** KeepBetween ******

        public static string KeepBetween(this string value, string prefix, string suffix)
        {
            return KeepBetween(value, prefix, suffix, true);
        }

        public static string KeepBetween(this string value, string prefix, string suffix, bool inclusive)
        {
            return KeepBetween(value, prefix, 0, suffix, 0, inclusive);
        }

        public static string KeepBetween(this string value, string prefix, int prefixInstance, string suffix, int suffixInstance)
        {
            return KeepBetween(value, prefix, prefixInstance, suffix, suffixInstance, true);
        }

        public static string KeepBetween(this string value, string prefix, int prefixInstance, string suffix, int suffixInstance, bool inclusive)
        {
            return KeepBetween(value, prefix, prefixInstance, inclusive, suffix, suffixInstance, inclusive);
        }

        public static string KeepBetween(this string value, string prefix, int prefixInstance, bool prefixInclusive, string suffix, int suffixInstance, bool suffixInclusive)
        {
            if (value.IndicesOf(prefix).Count > prefixInstance &&
                value.IndicesOf(suffix).Count > suffixInstance)
            {
                value = value.RemoveUntil(prefix, prefixInstance, !prefixInclusive).RemoveAt(suffix, suffixInstance, !suffixInclusive);
            }
            return value;
        }

        public static string KeepBetweenLast(this string value, string prefix, string suffix)
        {
            return KeepBetweenLast(value, prefix, suffix, false);
        }

        public static string KeepBetweenLast(this string value, string prefix, string suffix, bool inclusive)
        {
            if (value.LastIndexOf(prefix) < value.LastIndexOf(suffix))
            {
                value = value.RemoveUntilLast(prefix, !inclusive).RemoveAtLast(suffix, !inclusive);
            }
            return value;
        }

        // ****** RemoveBetween ******

        public static string RemoveBetween(this string value, string prefix, string suffix)
        {
            return RemoveBetween(value, prefix, suffix, false);
        }

        public static string RemoveBetween(this string value, string prefix, string suffix, bool inclusive)
        {
            return RemoveBetween(value, prefix, 0, suffix, 0, inclusive);
        }

        public static string RemoveBetween(this string value, string prefix, int prefixInstance, string suffix, int suffixInstance)
        {
            return RemoveBetween(value, prefix, prefixInstance, suffix, suffixInstance, false);
        }

        public static string RemoveBetween(this string value, string prefix, int prefixInstance, string suffix, int suffixInstance, bool inclusive)
        {
            return RemoveBetween(value, prefix, prefixInstance, inclusive, suffix, suffixInstance, inclusive);
        }

        public static string RemoveBetween(this string value, string prefix, int prefixInstance, bool prefixInclusive, string suffix, int suffixInstance, bool suffixInclusive)
        {

            if (value.IndicesOf(prefix).Count > prefixInstance &&
                value.IndicesOf(suffix).Count > suffixInstance)
            {
                int startIndex = value.IndicesOf(prefix)[prefixInstance];
                if (!prefixInclusive)
                {
                    startIndex += prefix.Length;
                }
                int count = value.IndicesOf(suffix)[suffixInstance] - startIndex;
                if (suffixInclusive)
                {
                    count += suffix.Length;
                }
                value = value.Remove(startIndex, count);
            }
            return value;
        }

        public static string RemoveBetweenAll(this string value, string prefix, string suffix, bool inclusive)
        {
            string oldValue = value;
            for (int i = 0; i < Extensions.LesserOf(value.IndicesOf(prefix).Count, value.IndicesOf(suffix).Count); i++)
            {
                if (value.IndicesOf(prefix)[i] < value.IndicesOf(suffix)[i])
                {
                    value = value.RemoveBetween(prefix, i, suffix, i, inclusive);
                }
            }
            return value;
        }

        // ****** RemoveInstance ******

        public static string RemoveInstance(this string value, string instance, int instanceIndex)
        {
            if (value.Contains(instance))
            {
                if (instanceIndex >= 0 & instanceIndex < value.IndicesOf(instance).Count)
                {
                    value = value.Remove(value.IndicesOf(instance)[instanceIndex], instance.Length);
                }
            }
            return value;
        }

        public static string RemoveFirst(this string value, string instance)
        {
            if (value.Contains(instance))
            {
                value = value.Remove(value.IndexOf(instance), instance.Length);
            }
            return value;
        }

        public static string RemoveLast(this string value, string instance)
        {
            if (value.Contains(instance))
            {
                value = value.Remove(value.LastIndexOf(instance), instance.Length);
            }
            return value;
        }

        public static string RemoveAllInstances(this string value, string instance)
        {
            if (value.Contains(instance))
            {
                value = value.Replace(instance, "");
            }
            return value;
        }

        #region RemoveAfter -- Deprecated

        /*
        public static string RemoveAfterFirst(this string value, string instance)
        {
            if (value.Contains(instance))
            {
                value = value.Remove(value.IndexOf(instance) + instance.Length);
            }
            return value;
        }

        public static string RemoveAfterLast(this string value, string instance)
        {
            if (value.Contains(instance))
            {
                value = value.Remove(value.LastIndexOf(instance) + instance.Length);
            }
            return value;
        }

        public static string RemoveAfter(this string value, string instance, int instanceIndex)
        {
            if (value.IndicesOf(instance).Count > instanceIndex)
            {
                value = value.Remove(value.IndicesOf(instance)[instanceIndex] + instance.Length);
            }
            return value;
        }
        */

        #endregion

        // ****** RemoveAt ******

        public static string RemoveAtFirst(this string value, string instance)
        {
            return RemoveAtFirst(value, instance, true);
        }

        public static string RemoveAtFirst(this string value, string instance, bool inclusive)
        {
            if (value.Contains(instance))
            {
                int instIndex = value.IndexOf(instance);
                if (!inclusive)
                {
                    instIndex += instance.Length;
                    if (value.Length <= instIndex)
                    {
                        return value;   //fix for when instance is at the end of the string
                    }
                }
                value = value.Remove(instIndex);
            }
            return value;
        }

        public static string RemoveAtLast(this string value, string instance)
        {
            return RemoveAtLast(value, instance, true);
        }

        public static string RemoveAtLast(this string value, string instance, bool inclusive)
        {
            if (value.Contains(instance))
            {
                int instIndex = value.LastIndexOf(instance);
                if (!inclusive)
                {
                    instIndex += instance.Length;
                    if (value.Length <= instIndex)
                    {
                        return value;   //fix for when instance is at the end of the string
                    }
                }
                value = value.Remove(instIndex);
            }
            return value;
        }

        public static string RemoveAt(this string value, string instance, int instanceIndex)
        {
            return RemoveAt(value, instance, instanceIndex, true);
        }

        public static string RemoveAt(this string value, string instance, int instanceIndex, bool inclusive)
        {
            if (value.IndicesOf(instance).Count > instanceIndex)
            {
                int instIndex = value.IndicesOf(instance)[instanceIndex];
                if (!inclusive)
                {
                    instIndex += instance.Length;
                    if (value.Length <= instIndex)
                    {
                        return value;   //fix for when instance is at the end of the string
                    }
                }
                value = value.Remove(instIndex);
            }
            return value;
        }

        // ****** RemoveUntil ******

        public static string RemoveUntilFirst(this string value, string instance)
        {
            return RemoveUntilFirst(value, instance, false);
        }

        public static string RemoveUntilFirst(this string value, string instance, bool inclusive)
        {
            if (value.Contains(instance))
            {
                int instIndex = value.IndexOf(instance);
                if (inclusive)
                {
                    instIndex += instance.Length;
                }
                value = value.Remove(0, instIndex);
            }
            return value;
        }

        public static string RemoveUntilLast(this string value, string instance)
        {
            return RemoveUntilLast(value, instance, false);
        }

        public static string RemoveUntilLast(this string value, string instance, bool inclusive)
        {
            if (value.Contains(instance))
            {
                int instIndex = value.LastIndexOf(instance);
                if (inclusive)
                {
                    instIndex += instance.Length;
                }
                value = value.Remove(0, instIndex);
            }
            return value;
        }

        public static string RemoveUntil(this string value, string instance, int instanceIndex, bool inclusive)
        {
            if (value.IndicesOf(instance).Count > instanceIndex)
            {
                int instIndex = value.IndicesOf(instance)[instanceIndex];
                if (inclusive)
                {
                    instIndex += instance.Length;
                }
                value = value.Remove(0, instIndex);
            }
            return value;
        }

        public static string Right(this string value, int numChars)
        {
            if (value.Length >= numChars)
            {
                value = value.Remove(0, value.Length - numChars);
            }
            return value;
        }

        public static string SqlSafe(this string value)
        {
            if (value == null)
            {
                return value;
            }
            return value
                    .RegexReplace("-{2,}", "-")                 // transforms multiple --- in - use to comment in sql scripts
                    .RegexReplace(@"[*/]+", string.Empty)      // removes / and * used also to comment in sql scripts
                    .RegexReplace(@"(;|\s)(exec|execute|select|insert|update|delete|create|alter|drop|rename|truncate|backup|restore)\s", string.Empty, RegexOptions.IgnoreCase);
        }

        public static string Suffix(this string value, string suffix)
        {
            return value + suffix;
        }

        public static byte[] ToByteArray(this string value, Encoding encoding)
        {
            byte[] rtn = encoding.GetBytes(value);
            return rtn;
        }

        public static string ToShortDateString(this string value)
        {
            DateTime tmp = new DateTime();
            if (DateTime.TryParse(value, out tmp))
            {
                value = tmp.ToShortDateString();
            }
            return value;
        }

        public static string Truncate(this string value, int maxLength)
        {
            if (value.Length > maxLength)
            {
                value = value.Remove(maxLength);
            }
            return value;
        }

        public static string UrlDecode(this string value)
        {
            value = HttpUtility.UrlDecode(value);
            return value;
        }

        public static string UrlEncode(this string value)
        {
            value = HttpUtility.UrlEncode(value);
            return value;
        }

        #region Query String Scrambling

        /*

        /// <summary>
        /// Scramble a message using a session-specific key
        /// </summary>
        public static string Scramble(this string message)
        {
            UTF8Encoding textConverter = new UTF8Encoding();
            RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();

            //Convert the data to a byte array.
            byte[] toEncrypt = textConverter.GetBytes(message);

            //Get an encryptor.
            ICryptoTransform encryptor =
                             rc2CSP.CreateEncryptor(Security.CurrentUser.ScrambleKey, Security.CurrentUser.ScrambleIV);

            //Encrypt the data.
            MemoryStream msEncrypt = new MemoryStream();
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor,
                                                     CryptoStreamMode.Write);

            //Write all data to the crypto stream and flush it.
            // Encode length as first 4 bytes
            byte[] length = new byte[4];
            length[0] = (byte)(message.Length & 0xFF);
            length[1] = (byte)((message.Length >> 8) & 0xFF);
            length[2] = (byte)((message.Length >> 16) & 0xFF);
            length[3] = (byte)((message.Length >> 24) & 0xFF);
            csEncrypt.Write(length, 0, 4);
            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();

            //Get encrypted array of bytes.
            byte[] encrypted = msEncrypt.ToArray();

            // Convert to Base64 string
            string b64 = Convert.ToBase64String(encrypted);

            // Protect against URLEncode/Decode problem
            string b64mod = b64.Replace('+', '@');

            // Return a URL encoded string
            return HttpUtility.UrlEncode(b64mod);
        }

        /// <summary>
        /// Unscramble a message in a session-specific key
        /// </summary>
        public static string Unscramble(this string scrambledMessage)
        {
            string rtn = "";
            if (scrambledMessage != null)
            {
                UTF8Encoding textConverter = new UTF8Encoding();
                RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();

                // URL decode , replace and convert from Base64
                string b64mod = HttpUtility.UrlDecode(scrambledMessage);
                // Replace '@' back to '+' (avoid URLDecode problem)
                string b64 = b64mod.Replace('@', '+');
                // Base64 decode
                byte[] encrypted = Convert.FromBase64String(b64);

                //Get a decryptor that uses the same key and IV as the encryptor.
                ICryptoTransform decryptor =
                                  rc2CSP.CreateDecryptor(Security.CurrentUser.ScrambleKey, Security.CurrentUser.ScrambleIV);

                //Now decrypt the previously encrypted message using the decryptor
                // obtained in the above step.
                MemoryStream msDecrypt = new MemoryStream(encrypted);
                CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor,
                    CryptoStreamMode.Read);

                byte[] fromEncrypt = new byte[encrypted.Length - 4];

                //Read the data out of the crypto stream.
                byte[] length = new byte[4];
                csDecrypt.Read(length, 0, 4);
                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
                int len = (int)length[0] | (length[1] << 8)
                    | (length[2] << 16) | (length[3] << 24);

                //Convert the byte array back into a string.
                rtn = textConverter.GetString(fromEncrypt).Substring(0, len);
            }
            return rtn;
        }
         * /

        /* --------------------------------------*/

        #endregion
    }

    public static class StringBuilderExtensions
    {
        public static StringBuilder Clear(this StringBuilder value)
        {
            value = value.Remove(0, value.Length);
            return value;
        }
    }
}
